package a_02_wizhi.P_proxy.cglib;

import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;


/**
 *
 * MethodInterceptor
 */
public class ProxyCglib  {


    public static Object createProxy(Object target,Class<? extends InvocationHandler> clazz) {
        Enhancer enhancer = new Enhancer();
        InvocationHandler invocationHandler = null;
        try {
//            InvocationHandler invocationHandler1 = clazz.newInstance();
            /**
             * 获取类字节码, 创建对象 clazz.newInstance();
             *
             * 获取构造器字节码, 创建对象 constructor.newInstance(target);
             */
            Constructor<? extends InvocationHandler> constructor = clazz.getConstructor(Object.class);
            invocationHandler= constructor.newInstance(target);
//            InvocationHandler invocationHandler1 = constructor.newInstance();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        enhancer.setCallback(invocationHandler);
        enhancer.setSuperclass(target.getClass());
        return enhancer.create();
    }




}
